import {Component, OnInit, ViewChild} from '@angular/core';
import {CropperComponent} from '../../../shared/cropper/cropper.component';
import {BannerService} from '../banner.service';
import {LoadingService} from '../../../shared/loading.service';
import {AlertService} from '../../../shared/alert.service';

@Component({
  selector: 'app-banner-add',
  templateUrl: './banner-add.component.html',
  styleUrls: ['./banner-add.component.scss']
})
export class BannerAddComponent implements OnInit {

    @ViewChild(CropperComponent) private cropperComponent: CropperComponent;
    // 图片是否上传
    public detailsPicture: Boolean = false;
    // 保存上传图片
    public cropperImg: any;
    // 按钮文字
    public uploadpictures: String = '上传图片并裁剪';
    public imgUrl = IMG_URL;

    public sort: any = '';
    public type = 1;


  constructor(
      public service: BannerService,
      public loading: LoadingService,
      public alert: AlertService
  ) { }

  ngOnInit() {
  }

    // 图片上传
    updateCroppersImg() {
        this.cropperComponent.show();
    }
//  获取图片
    commodityPictures (event) {
        this.cropperImg = event;
        this.uploadpictures = '重新上传';
        this.detailsPicture = true;
    }
//  删除图片
    deleteimg () {
        this.cropperImg = '';
        this.detailsPicture = false;
        this.uploadpictures = '上传图片并裁剪';

    }

    // 返回上一级页面
    returnList () {
        history.go(-1);
    }
    bannerSave() {
    if (!this.sort) {
      this.alert.show('排序不能为空');
      return;
    }
    if (!this.cropperImg) {
        this.alert.show('请选择图片');
        return;
    }
      this.loading.show();
      const params = {
        token: localStorage.token,
        image: this.cropperImg,
        sort: this.sort,
        type: this.type
      };
      this.service.addBanner(params).subscribe(res => {
        this.loading.hide();
        if (res['code'] === 0) {
          this.alert.show('新增成功');
          setTimeout(() => {
            history.go(-1);
          }, 1000);
        }
      });
    }

}
